#!/usr/bin/env python
# coding=utf-8
import os
import json 
import shutil
try:
    from .cvio import cvio
except:
    from cvio import cvio

def load_json(path):
    with open(path) as fp:
        return json.load(fp)

def write_json(json_info, path):
    with open(path, 'w') as fp:
        json.dump(json_info, fp)

def ISIMG(img):
    IMGEXT = ['.jpg', '.jpeg', '.png', '.tif', '.tiff']
    IMGEXT += [ext.upper() for ext in IMGEXT]
    for EXT in IMGEXT:
        if img.endswith(EXT):
            return True
    return False

def load_images(root):
    return [os.path.join(root, file) for file in os.listdir(root) if ISIMG(file)]

def semantic2instance(src, dst):

    if not os.path.exists(dst):
        os.makedirs(dst)
    img_ann_list = cvio.load_img_ann_list(src)
    num = len(img_ann_list)
    tbar = enumerate(img_ann_list, 1)
    for i, (img, ann) in tbar:
        print('[%d/%d, %.2f%%]' % (i, num, i / num * 100))
        ann_info = load_json(ann)
        shapes = ann_info['shapes']
        labels = dict()
        for shape in shapes:
            label = shape['label'].split('-')[0]
            if not label in labels.keys():
                labels[label] = 1
            else:
                labels[label] += 1
            shape['label'] = label + '-%d' % labels[label]
        imgsrc = img
        imgdst = os.path.join(dst, os.path.basename(img))
        anndst = os.path.join(dst, os.path.basename(ann))
        ann_info['imagePath'] = imgdst
        ann_info['imageData'] = None
        if not os.path.exists(imgdst):
            shutil.copy(img, imgdst)
        write_json(ann_info, anndst)


if __name__ == '__main__':
    src = r'F:\Dataset\jiujiang\20L\labeled\one'
    dst = r'F:\Dataset\jiujiang\20L\labeled\one'
    semantic2instance(src, dst)
